﻿#include<stdio.h>

#include<graphics.h>

#include<conio.h>

#define WIDTH 640
#define HEIGHT 480

#define SPEED 15//速度
#define SIZE 3 //初始节数

#define R 5


enum DIR
{
	UP = 72,
	DOWN = 80,
	LEFT = 75,
	RIGHT = 77
};


//1.描述蛇 -- 大小(节数)，速度，方向，坐标
struct Snack
{
	int size;
	int speed;
	int dir;
	POINT coor[100];//坐标,已经声明好的
}snack;

//2.游戏数据初始化
void GameInit()
{
	snack.size = SIZE;
	snack.speed = SPEED;
	snack.dir = UP;

	//计算居中的坐标
	int x = (WIDTH - R*2) / 2;
	int y = (HEIGHT - R*2) / 2;
	int r = R;
	for (int i = 0; i < snack.size; ++i)
	{
		snack.coor[i].x = x;
		snack.coor[i].y = y;
		x -= R * 2;
	}
}

void SetColor()
{
	setbkcolor(RGB(0, 162, 232));
	cleardevice();

	setfillcolor(RGB(34, 177, 76));
}

//3.画蛇
void GameDraw()
{
	BeginBatchDraw();

	SetColor();

	for (int i = 0; i < snack.size; ++i)
	{
		fillcircle(snack.coor[i].x, snack.coor[i].y, R);
	}
	FlushBatchDraw();

}

//4.蛇的移动 -- 使蛇的移动
//让蛇头动，后面的蛇身跟着动起来即可
void SnackMove()
{

	for (int i = snack.size - 1; i > 0; --i)//后面的蛇身都跟着前面的蛇身,从尾向头依次操作
	{
		snack.coor[i] = snack.coor[i - 1];
	}

	//根据方向来移动,所以4/5是相互影响的
	//穿墙
	switch (snack.dir)
	{
	case RIGHT:
		if (snack.coor[0].x + 10 >= WIDTH)
		{
			snack.coor[0].x = -R * 2;
		}
		snack.coor[0].x += snack.speed;
		break;
	case LEFT:
		if (snack.coor[0].x - 10 <= 0)
		{
			snack.coor[0].x = WIDTH + R * 2;
		}
		snack.coor[0].x -= snack.speed;
		break;
	case UP:
		if (snack.coor[0].y - 10 <= 0)
		{
			snack.coor[0].y = HEIGHT;
		}
		snack.coor[0].y -= snack.speed;
		break;//这里别忘记break
	case DOWN:
		if (snack.coor[0].y + 10 >= HEIGHT)
		{
			snack.coor[0].y = -R*2;
		}
		snack.coor[0].y += snack.speed;
		break;
	}

}

//5.键盘操作蛇 -- 改变蛇的方向
void KeyControl()
{
	if (kbhit())//判断是否有键盘输入
	{
		//不支持调头
		switch (_getch())//键盘输入
		{
		case UP:
		case 'W':
		case 'w':
			if (snack.dir != DOWN)
			{
				snack.dir = UP;
			}
			break;
		case DOWN:
		case 'S':
		case 's':		
			if (snack.dir != UP)
			{
				snack.dir = DOWN;
			}
			break;
		case LEFT:
		case 'A':
		case 'a':
			if (snack.dir != RIGHT)
			{
				snack.dir = LEFT;
			}
			break;
		case RIGHT:
		case 'R':
		case 'r':	
			if (snack.dir != LEFT)
			{
				snack.dir = RIGHT;
			}
			break;
		}
	}
}

int main()
{
	initgraph(WIDTH, HEIGHT, SHOWCONSOLE);

	GameInit();//游戏数据初始化

	while (true)
	{
		GameDraw();//画蛇
		SnackMove();//蛇的移动
		KeyControl();
		Sleep(20);
	}

	getchar();
	closegraph();
	return 0;
}